<template>
    <div class="competitions-container fade-in">
        <div class="page-header">
            <div class="header-content">
                <div class="title-section">
                    <h2 class="page-title">
                        <el-icon class="title-icon">
                            <Trophy />
                        </el-icon>
                        比赛项目管理
                    </h2>
                    <p class="page-subtitle">管理所有比赛项目信息和费用设置</p>
                </div>
                <el-button type="primary" class="add-button" @click="showAddDialog = true">
                    <el-icon>
                        <Plus />
                    </el-icon>
                    添加比赛项目
                </el-button>
            </div>
        </div>

        <div class="stats-cards">
            <el-card class="stat-card">
                <div class="stat-content">
                    <div class="stat-icon total">
                        <el-icon><Trophy /></el-icon>
                    </div>
                    <div class="stat-info">
                        <div class="stat-number">{{ competitions.length }}</div>
                        <div class="stat-label">总项目数</div>
                    </div>
                </div>
            </el-card>
            <el-card class="stat-card">
                <div class="stat-content">
                    <div class="stat-icon active">
                        <el-icon><CircleCheck /></el-icon>
                    </div>
                    <div class="stat-info">
                        <div class="stat-number">{{ activeCount }}</div>
                        <div class="stat-label">进行中</div>
                    </div>
                </div>
            </el-card>
            <el-card class="stat-card">
                <div class="stat-content">
                    <div class="stat-icon upcoming">
                        <el-icon><Clock /></el-icon>
                    </div>
                    <div class="stat-info">
                        <div class="stat-number">{{ upcomingCount }}</div>
                        <div class="stat-label">即将开始</div>
                    </div>
                </div>
            </el-card>
            <el-card class="stat-card">
                <div class="stat-content">
                    <div class="stat-icon total-fee">
                        <el-icon><Money /></el-icon>
                    </div>
                    <div class="stat-info">
                        <div class="stat-number">¥{{ avgFee }}</div>
                        <div class="stat-label">平均费用</div>
                    </div>
                </div>
            </el-card>
        </div>

        <el-card class="table-card">
            <template #header>
                <div class="card-header">
                    <span>比赛项目列表</span>
                    <div class="header-actions">
                        <el-input
                            v-model="searchQuery"
                            placeholder="搜索项目名称或类型"
                            class="search-input"
                            clearable
                            prefix-icon="Search"
                        />
                        <el-select v-model="statusFilter" placeholder="状态筛选" clearable class="status-filter">
                            <el-option label="全部" value="" />
                            <el-option label="进行中" value="进行中" />
                            <el-option label="即将开始" value="即将开始" />
                            <el-option label="已结束" value="已结束" />
                        </el-select>
                    </div>
                </div>
            </template>
            
            <el-table 
                :data="filteredCompetitions" 
                style="width: 100%" 
                :stripe="true" 
                :border="false"
                class="competitions-table"
                v-loading="loading">
                <el-table-column prop="name" label="项目名称" min-width="150">
                    <template #default="{ row }">
                        <div class="name-cell">
                            <el-icon class="competition-icon">
                                <Trophy />
                            </el-icon>
                            <span class="name-text">{{ row.name }}</span>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="type" label="项目类型" min-width="120">
                    <template #default="{ row }">
                        <el-tag :type="getTypeColor(row.type)" effect="light" class="type-tag">
                            {{ row.type }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="fee" label="报名费" min-width="100">
                    <template #default="{ row }">
                        <span class="fee-amount">¥{{ row.fee.toFixed(2) }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="startDate" label="开始日期" min-width="120">
                    <template #default="{ row }">
                        <span class="date-text">{{ formatDate(row.startDate) }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="endDate" label="结束日期" min-width="120">
                    <template #default="{ row }">
                        <span class="date-text">{{ formatDate(row.endDate) }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="status" label="状态" min-width="100">
                    <template #default="{ row }">
                        <el-tag 
                            :type="getStatusColor(row.status)" 
                            effect="light"
                            class="status-tag">
                            <el-icon class="status-icon">
                                <CircleCheck v-if="row.status === '进行中'" />
                                <Clock v-else-if="row.status === '即将开始'" />
                                <Close v-else />
                            </el-icon>
                            {{ row.status }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="participants" label="报名人数" min-width="100">
                    <template #default="{ row }">
                        <span class="participants-count">{{ row.participants || 0 }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="200" fixed="right">
                    <template #default="{ row }">
                        <div class="action-buttons">
                                                         <el-button type="primary" size="small" @click="editCompetitionHandler(row)" class="action-btn">
                                <el-icon><Edit /></el-icon>
                                编辑
                            </el-button>
                            <el-button type="success" size="small" @click="viewDetails(row)" class="action-btn">
                                <el-icon><View /></el-icon>
                                详情
                            </el-button>
                            <el-button type="danger" size="small" @click="deleteCompetition(row)" class="action-btn">
                                <el-icon><Delete /></el-icon>
                                删除
                            </el-button>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>

        <!-- 添加比赛项目对话框 -->
        <el-dialog 
            v-model="showAddDialog" 
            title="添加比赛项目" 
            width="700px" 
            class="add-dialog"
            :close-on-click-modal="false">
            <el-form :model="newCompetition" :rules="formRules" ref="formRef" label-width="100px" class="competition-form">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="项目名称" prop="name">
                            <el-input v-model="newCompetition.name" placeholder="请输入项目名称" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="项目类型" prop="type">
                            <el-select v-model="newCompetition.type" placeholder="请选择项目类型" style="width: 100%">
                                <el-option label="编程竞赛" value="编程竞赛" />
                                <el-option label="数学竞赛" value="数学竞赛" />
                                <el-option label="英语竞赛" value="英语竞赛" />
                                <el-option label="设计竞赛" value="设计竞赛" />
                                <el-option label="创新创业" value="创新创业" />
                                <el-option label="其他" value="其他" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="报名费" prop="fee">
                            <el-input-number 
                                v-model="newCompetition.fee" 
                                :min="0" 
                                :precision="2" 
                                :step="10" 
                                placeholder="请输入报名费"
                                style="width: 100%" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="状态" prop="status">
                            <el-select v-model="newCompetition.status" style="width: 100%">
                                <el-option label="即将开始" value="即将开始" />
                                <el-option label="进行中" value="进行中" />
                                <el-option label="已结束" value="已结束" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="开始日期" prop="startDate">
                            <el-date-picker 
                                v-model="newCompetition.startDate" 
                                type="date" 
                                placeholder="选择开始日期" 
                                style="width: 100%" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="结束日期" prop="endDate">
                            <el-date-picker 
                                v-model="newCompetition.endDate" 
                                type="date" 
                                placeholder="选择结束日期" 
                                style="width: 100%" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item label="项目描述" prop="description">
                    <el-input 
                        v-model="newCompetition.description" 
                        type="textarea" 
                        :rows="4"
                        placeholder="请输入项目描述" />
                </el-form-item>
                <el-form-item label="注意事项">
                    <el-input 
                        v-model="newCompetition.notes" 
                        type="textarea" 
                        :rows="3"
                        placeholder="请输入注意事项（可选）" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="showAddDialog = false">取消</el-button>
                    <el-button type="primary" @click="addCompetition" :loading="submitting">确定</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 编辑比赛项目对话框 -->
        <el-dialog 
            v-model="showEditDialog" 
            title="编辑比赛项目" 
            width="700px" 
            class="edit-dialog"
            :close-on-click-modal="false">
            <el-form :model="editCompetition" :rules="formRules" ref="editFormRef" label-width="100px" class="competition-form">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="项目名称" prop="name">
                            <el-input v-model="editCompetition.name" placeholder="请输入项目名称" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="项目类型" prop="type">
                            <el-select v-model="editCompetition.type" placeholder="请选择项目类型" style="width: 100%">
                                <el-option label="编程竞赛" value="编程竞赛" />
                                <el-option label="数学竞赛" value="数学竞赛" />
                                <el-option label="英语竞赛" value="英语竞赛" />
                                <el-option label="设计竞赛" value="设计竞赛" />
                                <el-option label="创新创业" value="创新创业" />
                                <el-option label="其他" value="其他" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="报名费" prop="fee">
                            <el-input-number 
                                v-model="editCompetition.fee" 
                                :min="0" 
                                :precision="2" 
                                :step="10" 
                                placeholder="请输入报名费"
                                style="width: 100%" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="状态" prop="status">
                            <el-select v-model="editCompetition.status" style="width: 100%">
                                <el-option label="即将开始" value="即将开始" />
                                <el-option label="进行中" value="进行中" />
                                <el-option label="已结束" value="已结束" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="开始日期" prop="startDate">
                            <el-date-picker 
                                v-model="editCompetition.startDate" 
                                type="date" 
                                placeholder="选择开始日期" 
                                style="width: 100%" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="结束日期" prop="endDate">
                            <el-date-picker 
                                v-model="editCompetition.endDate" 
                                type="date" 
                                placeholder="选择结束日期" 
                                style="width: 100%" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item label="项目描述" prop="description">
                    <el-input 
                        v-model="editCompetition.description" 
                        type="textarea" 
                        :rows="4"
                        placeholder="请输入项目描述" />
                </el-form-item>
                <el-form-item label="注意事项">
                    <el-input 
                        v-model="editCompetition.notes" 
                        type="textarea" 
                        :rows="3"
                        placeholder="请输入注意事项（可选）" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="showEditDialog = false">取消</el-button>
                    <el-button type="primary" @click="updateCompetition" :loading="submitting">保存修改</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { Plus, Trophy, CircleCheck, Clock, Money, Search, Edit, Delete, View, Close } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 模拟数据
const competitions = ref([
    {
        id: 1,
        name: '蓝桥杯程序设计大赛',
        type: '编程竞赛',
        fee: 300,
        startDate: '2024-03-15',
        endDate: '2024-04-15',
        status: '进行中',
        description: '全国性的程序设计竞赛，旨在培养大学生的编程能力',
        notes: '请携带有效身份证件参加比赛',
        participants: 156
    },
    {
        id: 2,
        name: '传智杯算法竞赛',
        type: '编程竞赛',
        fee: 88,
        startDate: '2024-05-01',
        endDate: '2024-06-01',
        status: '即将开始',
        description: '专注于算法设计和实现的竞赛',
        notes: '比赛分为省赛和国赛两个阶段',
        participants: 89
    },
    {
        id: 3,
        name: '全国大学生英语竞赛',
        type: '英语竞赛',
        fee: 50,
        startDate: '2024-04-20',
        endDate: '2024-05-20',
        status: '即将开始',
        description: '提高大学生英语综合应用能力',
        notes: '请提前30分钟到达考场',
        participants: 234
    },
    {
        id: 4,
        name: '数学建模竞赛',
        type: '数学竞赛',
        fee: 200,
        startDate: '2024-02-01',
        endDate: '2024-03-01',
        status: '已结束',
        description: '运用数学方法解决实际问题',
        notes: '团队参赛，每队3人',
        participants: 67
    }
])

const loading = ref(false)
const submitting = ref(false)
const searchQuery = ref('')
const statusFilter = ref('')
const formRef = ref(null)
const editFormRef = ref(null)

const showAddDialog = ref(false)
const showEditDialog = ref(false)

const newCompetition = ref({
    name: '',
    type: '',
    fee: 0,
    startDate: '',
    endDate: '',
    status: '即将开始',
    description: '',
    notes: ''
})

const editCompetition = ref({
    id: null,
    name: '',
    type: '',
    fee: 0,
    startDate: '',
    endDate: '',
    status: '',
    description: '',
    notes: ''
})

// 表单验证规则
const formRules = {
    name: [
        { required: true, message: '请输入项目名称', trigger: 'blur' },
        { min: 2, max: 50, message: '项目名称长度在2到50个字符之间', trigger: 'blur' }
    ],
    type: [
        { required: true, message: '请选择项目类型', trigger: 'change' }
    ],
    fee: [
        { required: true, message: '请输入报名费', trigger: 'blur' },
        { type: 'number', min: 0, message: '报名费不能为负数', trigger: 'blur' }
    ],
    status: [
        { required: true, message: '请选择状态', trigger: 'change' }
    ],
    startDate: [
        { required: true, message: '请选择开始日期', trigger: 'change' }
    ],
    endDate: [
        { required: true, message: '请选择结束日期', trigger: 'change' }
    ],
    description: [
        { required: true, message: '请输入项目描述', trigger: 'blur' }
    ]
}

// 统计数据
const activeCount = computed(() => competitions.value.filter(c => c.status === '进行中').length)
const upcomingCount = computed(() => competitions.value.filter(c => c.status === '即将开始').length)
const avgFee = computed(() => {
    if (competitions.value.length === 0) return '0.00'
    const total = competitions.value.reduce((sum, c) => sum + c.fee, 0)
    return (total / competitions.value.length).toFixed(2)
})

// 过滤数据
const filteredCompetitions = computed(() => {
    let filtered = competitions.value
    
    if (searchQuery.value) {
        const query = searchQuery.value.toLowerCase()
        filtered = filtered.filter(c => 
            c.name.toLowerCase().includes(query) || 
            c.type.toLowerCase().includes(query)
        )
    }
    
    if (statusFilter.value) {
        filtered = filtered.filter(c => c.status === statusFilter.value)
    }
    
    return filtered
})

// 格式化日期
const formatDate = (date) => {
    if (!date) return '-'
    return new Date(date).toLocaleDateString('zh-CN')
}

// 获取类型颜色
const getTypeColor = (type) => {
    const colors = {
        '编程竞赛': 'primary',
        '数学竞赛': 'success',
        '英语竞赛': 'warning',
        '设计竞赛': 'info',
        '创新创业': 'danger',
        '其他': ''
    }
    return colors[type] || ''
}

// 获取状态颜色
const getStatusColor = (status) => {
    const colors = {
        '进行中': 'success',
        '即将开始': 'warning',
        '已结束': 'info'
    }
    return colors[status] || ''
}

// 添加比赛项目
const addCompetition = async () => {
    if (!formRef.value) return
    
    try {
        await formRef.value.validate()
        submitting.value = true
        
        // 模拟API调用延迟
        await new Promise(resolve => setTimeout(resolve, 1000))
        
        const newComp = {
            id: Date.now(),
            ...newCompetition.value,
            participants: 0
        }
        
        competitions.value.push(newComp)
        showAddDialog.value = false
        ElMessage.success('添加成功')
        
        // 重置表单
        newCompetition.value = {
            name: '',
            type: '',
            fee: 0,
            startDate: '',
            endDate: '',
            status: '即将开始',
            description: '',
            notes: ''
        }
    } catch (error) {
        console.error(error)
        ElMessage.error('请填写正确的信息')
    } finally {
        submitting.value = false
    }
}

// 编辑比赛项目
const editCompetitionHandler = (row) => {
    editCompetition.value = { ...row }
    showEditDialog.value = true
}

// 更新比赛项目
const updateCompetition = async () => {
    if (!editFormRef.value) return
    
    try {
        await editFormRef.value.validate()
        submitting.value = true
        
        // 模拟API调用延迟
        await new Promise(resolve => setTimeout(resolve, 1000))
        
        const index = competitions.value.findIndex(c => c.id === editCompetition.value.id)
        if (index !== -1) {
            competitions.value[index] = { ...editCompetition.value }
        }
        
        showEditDialog.value = false
        ElMessage.success('修改成功')
        
        // 重置编辑表单
        editCompetition.value = {
            id: null,
            name: '',
            type: '',
            fee: 0,
            startDate: '',
            endDate: '',
            status: '',
            description: '',
            notes: ''
        }
    } catch (error) {
        console.error(error)
        ElMessage.error('请填写正确的信息')
    } finally {
        submitting.value = false
    }
}

// 删除比赛项目
const deleteCompetition = (row) => {
    ElMessageBox.confirm(
        `确定要删除比赛项目 "${row.name}" 吗？`,
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(() => {
        const index = competitions.value.findIndex(c => c.id === row.id)
        if (index !== -1) {
            competitions.value.splice(index, 1)
        }
        ElMessage.success('删除成功')
    })
}

// 查看详情
const viewDetails = (row) => {
    ElMessage.info(`查看 ${row.name} 的详细信息`)
    // 这里可以打开详情对话框或跳转到详情页面
}

onMounted(() => {
    loading.value = true
    // 模拟加载延迟
    setTimeout(() => {
        loading.value = false
    }, 1000)
})
</script>

<style scoped>
.competitions-container {
    animation: fadeIn 0.5s ease-out;
}

.page-header {
    margin-bottom: var(--spacing-xl);
}

.header-content {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    gap: var(--spacing-lg);
}

.title-section {
    flex: 1;
}

.page-title {
    display: flex;
    align-items: center;
    gap: var(--spacing-md);
    margin: 0 0 var(--spacing-sm) 0;
    font-size: 1.75rem;
    font-weight: 700;
    color: var(--text-primary);
}

.title-icon {
    font-size: 1.5rem;
    color: var(--primary-color);
}

.page-subtitle {
    margin: 0;
    color: var(--text-secondary);
    font-size: 0.9rem;
}

.add-button {
    display: flex;
    align-items: center;
    gap: var(--spacing-sm);
    padding: var(--spacing-md) var(--spacing-lg);
    font-weight: 500;
    border-radius: var(--radius-lg);
    box-shadow: var(--shadow-md);
}

.stats-cards {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: var(--spacing-lg);
    margin-bottom: var(--spacing-xl);
}

.stat-card {
    border-radius: var(--radius-lg);
    transition: all 0.3s ease;
    cursor: pointer;
}

.stat-card:hover {
    transform: translateY(-4px);
    box-shadow: var(--shadow-xl);
}

.stat-content {
    display: flex;
    align-items: center;
    gap: var(--spacing-lg);
    padding: var(--spacing-md);
}

.stat-icon {
    width: 60px;
    height: 60px;
    border-radius: var(--radius-lg);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.5rem;
    color: white;
}

.stat-icon.total {
    background: linear-gradient(135deg, var(--primary-color), var(--primary-light));
}

.stat-icon.active {
    background: linear-gradient(135deg, var(--success-color), #34d399);
}

.stat-icon.upcoming {
    background: linear-gradient(135deg, var(--warning-color), #fbbf24);
}

.stat-icon.total-fee {
    background: linear-gradient(135deg, var(--danger-color), #f87171);
}

.stat-info {
    flex: 1;
}

.stat-number {
    font-size: 1.75rem;
    font-weight: 700;
    color: var(--text-primary);
    line-height: 1;
}

.stat-label {
    font-size: 0.875rem;
    color: var(--text-secondary);
    margin-top: var(--spacing-xs);
}

.table-card {
    border-radius: var(--radius-xl);
    box-shadow: var(--shadow-lg);
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-weight: 600;
    color: var(--text-primary);
}

.header-actions {
    display: flex;
    align-items: center;
    gap: var(--spacing-md);
}

.search-input {
    width: 250px;
}

.status-filter {
    width: 150px;
}

.competitions-table {
    border-radius: var(--radius-lg);
    overflow: hidden;
}

.name-cell {
    display: flex;
    align-items: center;
    gap: var(--spacing-sm);
}

.competition-icon {
    color: var(--primary-color);
    font-size: 1.2rem;
}

.name-text {
    font-weight: 500;
    color: var(--text-primary);
}

.type-tag {
    border-radius: var(--radius-md);
    font-weight: 500;
}

.fee-amount {
    font-weight: 600;
    color: var(--danger-color);
    font-size: 1.1rem;
}

.date-text {
    color: var(--text-secondary);
    font-size: 0.9rem;
}

.status-tag {
    display: flex;
    align-items: center;
    gap: var(--spacing-xs);
    border-radius: var(--radius-md);
    font-weight: 500;
}

.status-icon {
    font-size: 0.875rem;
}

.participants-count {
    font-weight: 600;
    color: var(--primary-color);
    font-size: 1.1rem;
}

.action-buttons {
    display: flex;
    gap: var(--spacing-sm);
}

.action-btn {
    display: flex;
    align-items: center;
    gap: var(--spacing-xs);
    border-radius: var(--radius-md);
    transition: all 0.3s ease;
}

.action-btn:hover {
    transform: translateY(-1px);
    box-shadow: var(--shadow-md);
}

.add-dialog,
.edit-dialog {
    border-radius: var(--radius-xl);
}

.competition-form {
    padding: var(--spacing-lg) 0;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: var(--spacing-md);
}

/* 响应式设计 */
@media (max-width: 768px) {
    .header-content {
        flex-direction: column;
        align-items: stretch;
        gap: var(--spacing-md);
    }
    
    .stats-cards {
        grid-template-columns: repeat(2, 1fr);
        gap: var(--spacing-md);
    }
    
    .card-header {
        flex-direction: column;
        align-items: stretch;
        gap: var(--spacing-md);
    }
    
    .header-actions {
        flex-direction: column;
        align-items: stretch;
    }
    
    .search-input,
    .status-filter {
        width: 100%;
    }
}

@media (max-width: 480px) {
    .stats-cards {
        grid-template-columns: 1fr;
    }
    
    .page-title {
        font-size: 1.5rem;
    }
    
    .stat-content {
        padding: var(--spacing-sm);
    }
    
    .stat-icon {
        width: 50px;
        height: 50px;
        font-size: 1.25rem;
    }
    
    .stat-number {
        font-size: 1.5rem;
    }
}
</style>
